package com.zomiot.portal.user.controller;

import cn.dev33.satoken.stp.StpUtil;

import com.zomiot.portal.common.result.Result;
import com.zomiot.portal.user.dto.LoginRequest;
import com.zomiot.portal.user.dto.RegisterRequest;
import com.zomiot.portal.user.dto.UserInfoVO;
import com.zomiot.portal.user.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 认证相关接口（登录、注册、登出）
 *
 * @author Joash_Yi
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;

    /**
     * 用户注册
     *
     * @param request 注册请求
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<UserInfoVO> register(@Valid @RequestBody RegisterRequest request) {
        log.info("【注册请求】username={}", request.getUsername());
        UserInfoVO userInfo = userService.register(request);
        return Result.success(userInfo, "注册成功");
    }

    /**
     * 用户登录
     *
     * @param request 登录请求
     * @return 登录结果（包含Token）
     */
    @PostMapping("/login")
    public Result<UserInfoVO> login(@Valid @RequestBody LoginRequest request) {
        log.info("【登录请求】username={}", request.getUsername());
        UserInfoVO userInfo = userService.login(request);
        return Result.success(userInfo, "登录成功");
    }

    /**
     * 用户登出
     *
     * @return 登出结果
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        log.info("【登出请求】userId={}", StpUtil.getLoginId());
        userService.logout();
        return Result.success(null, "登出成功");
    }

    /**
     * 检查登录状态
     *
     * @return 是否已登录
     */
    @GetMapping("/check")
    public Result<Boolean> checkLogin() {
        boolean isLogin = StpUtil.isLogin();
        return Result.success(isLogin, isLogin ? "已登录" : "未登录");
    }

    /**
     * 获取当前Token信息
     *
     * @return Token信息
     */
    @GetMapping("/token-info")
    public Result<String> getTokenInfo() {
        if (!StpUtil.isLogin()) {
            return Result.error("未登录");
        }
        String tokenInfo = "Token: " + StpUtil.getTokenValue() +
                           ", UserId: " + StpUtil.getLoginId() +
                           ", Timeout: " + StpUtil.getTokenTimeout();
        return Result.success(tokenInfo);
    }
}